﻿<%@ Page Language="C#" AutoEventWireup="true" Inherits="EPiCode.GoogleMapsLocation.LocationSelectionPage" %>
<%@ Register TagPrefix="EPiServerUI" Namespace="EPiServer.UI.WebControls" Assembly="EPiServer.UI" %>
<%@ Register TagPrefix="EPiServerScript" Namespace="EPiServer.ClientScript.WebControls" Assembly="EPiServer" %>
<%@ Register TagPrefix="EPiServerScript" Namespace="EPiServer.UI.ClientScript.WebControls" Assembly="EPiServer.UI" %>

<asp:Content ContentPlaceHolderID="HeaderContentRegion" runat="server">
    <base target="_self" />
</asp:Content>
<asp:Content ContentPlaceHolderID="FullRegion" runat="server">
    <div id="map" style="width: 485px; height: 400px"></div>
    <asp:Panel DefaultButton="buttonSearch" style="margin-top: 8px; position: relative;" runat="server">
        <input id="searchTextBox" class="episize240" style="width: 409px; margin-right: 10px;" type="text" />
        <span style="position: absolute; top: -2px;">
            <EPiServerUI:ToolButton ID="buttonSearch" GeneratesPostBack="False" runat="server" OnClientClick="searchAddress(document.getElementById('searchTextBox').value); return false;" 
                Text="<%$ Resources: EPiServer, button.search %>" ToolTip="<%$ Resources: EPiServer, button.search %>" SkinID="Search" />
        </span>
    </asp:Panel>
    
    <div style="position: absolute; bottom: 25px; width: 485px; text-align: right;">
        <asp:HiddenField ID="hiddenFieldLocation" runat="server" />
        <EPiServerUI:ToolButton GeneratesPostBack="False" runat="server" OnClientClick="onOK();" Text="<%$ Resources: EPiServer, button.select %>" ToolTip="<%$ Resources: EPiServer, button.select %>" SkinID="Check" />
        <EPiServerUI:ToolButton GeneratesPostBack="False" runat="server" OnClientClick="onNothing();" Text="<%$ Resources: EPiServer, button.clear %>" ToolTip="<%$ Resources: EPiServer, button.clear %>" SkinID="Delete" />
        <EPiServerUI:ToolButton GeneratesPostBack="False" runat="server" OnClientClick="onCancel();" Text="<%$ Resources: EPiServer, button.cancel %>" ToolTip="<%$ Resources: EPiServer, button.cancel %>" SkinID="Cancel" />
    </div>
    

    <script type="text/javascript">
        //<![CDATA[
        var map = null;
        var geocoder = null;
        var marker = null;
        var infowindow = null;

        function initialize() {
			var mapOptions = {
			  mapTypeId: google.maps.MapTypeId.ROADMAP
			};
        	
            map = new google.maps.Map(document.getElementById("map"), mapOptions);
            infowindow = new google.maps.InfoWindow();
        	var center = new google.maps.LatLng(<%= DefaultCenter %>);
            var zoomLevel = <%= DefaultZoomLevel %>;
            if (document.getElementById("<%= hiddenFieldLocation.ClientID %>").value.length > 0) {
                var coordinates = document.getElementById("<%= hiddenFieldLocation.ClientID %>").value;
                coordinates = coordinates.substring(coordinates.indexOf("(") + 1, coordinates.indexOf(")"));
                zoomLevel = document.getElementById("<%= hiddenFieldLocation.ClientID %>").value;
                zoomLevel = parseInt(zoomLevel.substring(zoomLevel.indexOf(")")+1));

            	coordinates = coordinates.split(",");
                center = new google.maps.LatLng(coordinates[0], coordinates[1]);
                addMarker(center);

                var address = document.getElementById("<%= hiddenFieldLocation.ClientID %>").value;
                address = address.substring(0, address.indexOf(" ("));
                showInfoWindow(address);
                document.getElementById("searchTextBox").value = address;
                if (isNaN(zoomLevel)) {
                	zoomLevel = <%= CurrentLocationZoomLevel %> ;
                }
            }
            map.setCenter(center);
        	map.setZoom(zoomLevel);
            //map.addControl(new GLargeMapControl3D());
            //map.addControl(new GNavLabelControl());

            geocoder = new google.maps.Geocoder();

            google.maps.event.addListener(map, "click", getAddressFromClick);
            google.maps.event.addListener(map, "zoom_changed", updateZoom);
        	
        }
        google.maps.event.addDomListener(window, 'load', initialize);

        function searchAddress(address) {
            if (geocoder) {
                geocoder.geocode(
					{address : address},
					function(response, status) {

						if (status != "OK") {
							alert(address + " not found");
						} else {

							var point = response[0].geometry.location;
							
							map.setCenter(point);
							map.setZoom(13);
							
							if (!marker) {
								addMarker(point);
							} else {
								marker.setPosition(point);
							}
							showInfoWindow(address);
							updateLocationField(address);
						}
					}
				);
            }
        }

        function addMarker(point) {
            marker = new google.maps.Marker({ position: point, draggable: true, map: map });
            google.maps.event.addListener(marker, "dragend", markerDragged);
        }
        function markerDragged() {
            var newPoint = marker.getPosition();
            getAddress(newPoint);
        }
        function getAddressFromClick(event) {
            getAddress(event.latLng);
        }
        function showInfoWindow(content) {
        	infowindow.setContent(content);
       		infowindow.open(map,marker);
        }

        function getAddress(latlng) {
            if (latlng != null) {
                geocoder.geocode(
					{location : latlng},
					function(response, status) {


						if (status != "OK") {
							alert("address not found");
						} else {
							var address = response[0].formatted_address;

							var point = new google.maps.LatLng(latlng.lat(), latlng.lng());
							if (!marker) {
								addMarker(point);
							}
							else {
								marker.setPosition(point);
							}
							showInfoWindow(address);
							document.getElementById("searchTextBox").value = address;
							updateLocationField(address);
						}
					}
				);
            	
            }
        }

        function updateZoom() {
			if (marker != null) {
        		var address = document.getElementById("searchTextBox").value;
				updateLocationField(address);
			}
        }

        function updateLocationField(address) {
            var markerLatitude = marker.getPosition().lat();
            var markerLongitude = marker.getPosition().lng();
            var location = address + " (" + markerLatitude + "," + markerLongitude + ")" + map.getZoom();
            document.getElementById("<%= hiddenFieldLocation.ClientID %>").value = location;
        }


    	var returnValue = false;

    	function onOK() {
    	    var location = document.getElementById("<%= hiddenFieldLocation.ClientID %>").value;
    	    EPi.GetDialog().dialogArguments.getElementById('<%= Request.QueryString["valueid"] %>').value = location;
    	    EPi.GetDialog().dialogArguments.getElementById('<%= Request.QueryString["displayid"] %>').value = location;
			EPi.GetDialog().Close(true);
		}

		function onNothing()
		{
			EPi.GetDialog().dialogArguments.getElementById('<%= Request.QueryString["valueid"] %>').value = '';
			EPi.GetDialog().dialogArguments.getElementById('<%= Request.QueryString["displayid"] %>').value = '';
			EPi.GetDialog().Close(true);
		}

		function onCancel()
		{
			EPi.GetDialog().Close(false);
		}

		function onLoad()
		{
			window.focus();
			if (this.activeItem) 
			{
				this.activeItem.scrollIntoView(false);
			}
		}
		
		function SetValues(value, info)
		{
			var doc = EPi.GetDialog().dialogArguments;

			returnValue = true;
		}	
		//]]>
    </script>
</asp:Content>
